package com.zhang.edu.realtime.utils;

import com.zhang.edu.realtime.bean.TransientSink;
import com.zhang.edu.realtime.common.EduConfig;
import org.apache.flink.connector.jdbc.JdbcConnectionOptions;
import org.apache.flink.connector.jdbc.JdbcExecutionOptions;
import org.apache.flink.connector.jdbc.JdbcSink;
import org.apache.flink.connector.jdbc.JdbcStatementBuilder;
import org.apache.flink.streaming.api.functions.sink.SinkFunction;

import java.lang.reflect.Field;

public class ClickHouseUtil {
    public static <T> SinkFunction<T> getJdbcSink(String sql) {
        return JdbcSink.<T>sink(
                sql,
                (JdbcStatementBuilder<T>) (preparedStatement, obj) -> {
                    Field[] declaredFields = obj.getClass().getDeclaredFields();
                    int skipNum = 0;
                    for (int i = 0; i < declaredFields.length; i++) {
                        Field declaredField = declaredFields[i];
                        TransientSink transientSink = declaredField.getAnnotation(TransientSink.class);
                        if (transientSink != null) {
                            skipNum++;
                            continue;
                        }
                        declaredField.setAccessible(true);
                        try {
                            Object value = declaredField.get(obj);
                            preparedStatement.setObject(i + 1 - skipNum, value);
                        } catch (IllegalAccessException e) {
                            System.out.println("ClickHouse 数据插入 SQL 占位符传参异常 ~");
                            e.printStackTrace();
                        }
                    }
                },
                JdbcExecutionOptions.builder()
                        .withBatchIntervalMs(5000L)
                        .withBatchSize(5)
                        .build(),
                new JdbcConnectionOptions.JdbcConnectionOptionsBuilder()
                        .withDriverName(EduConfig.CLICKHOUSE_DRIVER)
                        .withUrl(EduConfig.CLICKHOUSE_URL)
                        .build()
        );
    }
}
